package com.op.teachingliteapp.sender.runnable;

import android.view.View;
import android.widget.ProgressBar;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.security.Permission;

import android.util.Log;
import android.widget.ArrayAdapter;

import com.op.teachingliteapp.sender.Constants;
import com.op.teachingliteapp.sender.handler.DeviceScanHandler;


/**
 * Created by Genji on 2015/5/16.
 */
public class DeviceScanRunnable implements Runnable {
    private ArrayAdapter adapter;
    private ProgressBar progressBar;


    public DeviceScanRunnable(ArrayAdapter adapter,ProgressBar progressBar) {
        this.adapter = adapter;
        this.progressBar=progressBar;
        this.progressBar.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
    }



    @Override
    public void run() {
          this.progressBar.post(new Runnable() {
              @Override
              public void run() {
                  progressBar.setVisibility(View.VISIBLE);
              }
          });
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true).handler(new DeviceScanHandler(adapter));
            Channel channel = bootstrap.bind(0).sync().channel();
            DatagramPacket datagramPacket =new DatagramPacket(Unpooled.copiedBuffer("is reciver ?", CharsetUtil.UTF_8),new InetSocketAddress("255.255.255.255",Constants.deviceScanPort));
            channel.writeAndFlush(datagramPacket).sync();
            if (!channel.closeFuture().await(5000)) {
                Log.i("connect time out","5s");
                this.progressBar.post(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setVisibility(View.GONE);
                    }
                });
            }


        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
//            group.shutdownGracefully();

        }

    }
}
